package org.example.analysis.util;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.stream.Collectors;

/**
 * 数据库工具类
 */
@Slf4j
public class DatabaseUtil {
    private static final String DB_URL = "jdbc:sqlite:code_analysis.db";
    
    /**
     * 获取数据库连接
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(DB_URL);
    }
    
    /**
     * 初始化数据库
     */
    public static void initDatabase() {
        try (Connection conn = getConnection()) {
            // 读取schema.sql文件
            String schema = readSchemaFile();
            
            // 执行建表语句
            try (Statement stmt = conn.createStatement()) {
                for (String sql : schema.split(";")) {
                    if (!sql.trim().isEmpty()) {
                        stmt.execute(sql);
                    }
                }
            }
            log.info("数据库初始化成功");
        } catch (SQLException | IOException e) {
            log.error("数据库初始化失败", e);
            throw new RuntimeException("数据库初始化失败", e);
        }
    }
    
    /**
     * 读取schema.sql文件
     */
    private static String readSchemaFile() throws IOException {
        try (InputStream is = DatabaseUtil.class.getClassLoader().getResourceAsStream("schema.sql")) {
            if (is == null) {
                throw new IOException("无法找到schema.sql文件");
            }
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
                return reader.lines().collect(Collectors.joining("\n"));
            }
        }
    }
} 